package org.piaohao.howtodoit.usermanager;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginInterceptor implements Interceptor {

    @Override
    public void intercept(Invocation inv) {
        Controller controller = inv.getController();
        if (controller.getSession().getAttribute(MainApp.Const.SESSION_KEY) != null) {
            inv.invoke();
            return;
        }
        HttpServletResponse response = controller.getResponse();
        response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
        response.setHeader("content-type", "application/json");
        try {
            response.getWriter().write(JSONUtil.toJsonStr(MapUtil.of("errorMsg", "need login")));
            response.getWriter().flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
